package com.ssd.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.ssd.serialize.BigDecimalSerializer;
import com.ssd.serialize.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


/**
 * 配置Jackson的序列化和反序列化行为
 * 该配置类在ObjectMapper类存在时生效
 */
@Configuration
//@ConditionalOnClass(ObjectMapper.class)
public class JsonConfig {
    /**
     * 自定义Jackson2ObjectMapperBuilderCustomizer配置
     * 用于全局定制ObjectMapper的序列化和反序列化行为
     *
     * @return Jackson2ObjectMapperBuilderCustomizer实例
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return jacksonObjectMapperBuilder -> {
            // 定义日期时间格式化器
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 设置时区为东八区
            jacksonObjectMapperBuilder.timeZone("GMT+8");
            // 配置LocalDateTime的序列化和反序列化器
            jacksonObjectMapperBuilder.serializers(new com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer(dateTimeFormatter));
            jacksonObjectMapperBuilder.deserializers(new LocalDateTimeDeserializer(dateTimeFormatter));
            // 配置Long和BigInteger类型转换为字符串序列化，防止精度丢失
            jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance);
            jacksonObjectMapperBuilder.serializerByType(BigInteger.class, ToStringSerializer.instance);
            // 配置BigDecimal的序列化方式，保留两位小数
            jacksonObjectMapperBuilder.serializerByType(BigDecimal.class, BigDecimalSerializer.instance);
            // 配置LocalDateTime的序列化格式为yyyy-MM-dd HH:mm:ss
            jacksonObjectMapperBuilder.serializerByType(LocalDateTime.class, LocalDateTimeSerializer.instance);
        };
    }
}

